package com.ztesoft.web.checkup.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.DateUtils;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.po.DmPlanPO;
import com.ztesoft.web.baseconfig.db.po.DmStrategyPO;
import com.ztesoft.web.checkup.CheckUpFileTask;
import com.ztesoft.web.common.DMSConstant;
import com.ztesoft.web.common.Util;
import com.ztesoft.web.common.customdb.dao.DmTaskStageCustomDao;
import com.ztesoft.web.common.customdb.dao.dto.DmTaskStageDto;
import com.ztesoft.web.filecommon.db.po.DmSrcFilePO;
import com.ztesoft.web.taskgenerator.db.po.DmTaskPO;


/**
 * 文件体检
 * @version 1.0
 */

@Service
public class CheckUpFileServiceImpl {
	
	private static final ZTEsoftLogManager LOGGER = ZTEsoftLogManager
	            .getLogger(CheckUpFileServiceImpl.class);
	
	@Autowired
	private DmTaskStageCustomDao taskStageCustomDao;
	
	public String checkUp(DmPlanPO planPO, DmTaskPO taskPO, DmStrategyPO strategyPO, DmSrcFilePO srcTablePO) {
		String checkState = DMSConstant.Status.SUCCESS.getState();
		LOGGER.debug("|查询任务环节列表|strategyId={0},taskId={1}", strategyPO.getDmStrategyId(), taskPO.getDmTaskId());
		List<CheckUpFileTask> checkUpFileTaskList = new ArrayList<CheckUpFileTask>();
		List<DmTaskStageDto> taskStageList = taskStageCustomDao.selectTaskStageList(taskPO.getDmTaskId(), 
				strategyPO.getDmStrategyId(), DMSConstant.STAGE_CHECKUP,"00T");
		LOGGER.info("|查询待体检任务环节列表|\r\n{0}",taskStageList);
		if (Utils.isEmpty(taskStageList)) {
			return checkState;//
		}
		//如果是采用自定义脚本处理(DM_SRC_FILE.script_path非空)，走自定义脚本流程
		if(Utils.notEmpty(srcTablePO.getScriptPath())){
			return checkState;//
		}
		for (DmTaskStageDto taskStageDto : taskStageList) {
			checkUpFileTaskList.add(new CheckUpFileTask(srcTablePO, taskStageDto, taskPO.getDmTaskId(), strategyPO, planPO));
		}
		// 体检数据为空 或 统计数据异常
		if ((DMSConstant.Status.DATA_NULL.getState().equals(checkState)
				||DMSConstant.Status.FALSE.getState().equals(checkState)) && Utils.isEmpty(checkUpFileTaskList)){
			return checkState;
		}
		//ExecutorService线程处理
		int concurrentCount = strategyPO.getConcurrentNumber()>=taskStageList.size() ? 
				taskStageList.size() : strategyPO.getConcurrentNumber();
				return execute(strategyPO, srcTablePO, checkState, concurrentCount, checkUpFileTaskList);
	}
	private String execute(DmStrategyPO strategyPO, DmSrcFilePO srcFilePO,String checkState, int nThreads,
			List<CheckUpFileTask> checkUpFileTask) {
		List<Future<DmTaskStageDto>> futures = null;
		ExecutorService executor = null;
		int sucessInt = 0,failInt = 0,stopInt = 0, sysStopInt = 0, cancelInt = 0;
		try {
			executor = Executors.newFixedThreadPool(nThreads);
			futures = executor.invokeAll(checkUpFileTask);
			for (Future<DmTaskStageDto> future : futures) {
				checkState = future.get().getCheckState();
				LOGGER.info("|体检|{0}表END|:::{1}",future.get().getCheckObjName(), checkState);
				if (DMSConstant.SUCCESS.equals(checkState)) {
					future.get().setState(DMSConstant.Status.SUCCESS.getState());
					sucessInt = sucessInt + 1;
				} else if (DMSConstant.FAIL.equals(checkState)){
					future.get().setState(DMSConstant.Status.FALSE.getState());
					future.get().setStage(null);
					failInt = failInt + 1;
				} else if (DMSConstant.Status.CANCEL.getState().equals(checkState)) {
					cancelInt = cancelInt + 1;
				} else if (DMSConstant.Status.PAUSE.getState().equals(checkState)) {
					stopInt = stopInt + 1;
				} else if (DMSConstant.Status.SYSPAUSE.getState().equals(checkState)) {
					sysStopInt = sysStopInt + 1;
				}
				
				if (DMSConstant.SUCCESS.equals(checkState)|| DMSConstant.FAIL.equals(checkState)) {//更新环节
					future.get().setTaskStartTime(null);//避免数据插入
					future.get().setTaskEndTime(DateUtils.getDBCurrentTime());
					future.get().setStateDate(DateUtils.getDBCurrentTime());
					taskStageCustomDao.updateTaskStageState(future.get());
					
					future.get().setTotalRecordCount(future.get().getTotalRecordCount());
					future.get().setTotalDataSize(future.get().getTotalDataSize());
					taskStageCustomDao.updateTaskStage(future.get());//
				}
			}
			LOGGER.debug("checkup{0} end...",strategyPO.getDmStrategyId());
			LOGGER.info("|++===体检服务|任务END..sucessInt:{0},failInt:{1},stopInt:{2},sysStopInt:{3},cancelInt:{4}",sucessInt,failInt,stopInt,sysStopInt,cancelInt);
			if (cancelInt > 0){
				checkState = DMSConstant.Status.CANCEL.getState();//取消
			} else if (sysStopInt > 0) {
				checkState = DMSConstant.Status.SYSPAUSE.getState();//系统暂停
			} else if (stopInt > 0) {
				checkState = DMSConstant.Status.PAUSE.getState();//暂停
			} else if (failInt > 0) {
				checkState = DMSConstant.Status.FALSE.getState();//失败
			} else {
				checkState = DMSConstant.Status.SUCCESS.getState();//成功
			}
		} catch (InterruptedException e) {
			LOGGER.error("", e);
			checkState = DMSConstant.Status.FALSE.getState();
		} catch (ExecutionException e) {
			LOGGER.error("", e);
			checkState = DMSConstant.Status.FALSE.getState();
		} finally {
			executor.shutdown();
		}
		return checkState;
	};

}
